'use strict';

const BUCKET = 'fc-ws';
const WORK_DIR = 'fc-chat/';
const AG_NOTIFY_URL = 'http://api.dingxiaolin.com/notify';
const AG_APP_KEY = '203812402';
const AG_APP_SECRET = 'rfhdp7onpkcwbciplr9k8josb0ao1f1m';
const request = require('request-promise')
var OSS = require('ali-oss');

module.exports.send = function (event, context, callback) {
  console.log('event: %s', event);
  var evt = JSON.parse(event);
  var deviceId = evt['queryParameters']['deviceId'];
  var message = evt['queryParameters']['msg'];
  //   var message = evt['body'];
  var ossClient = getOSSClient(context);
  var resp = {
    'isBase64Encoded': 'false',
    'statusCode': '200',
    'body': {
      'deviceId': deviceId,
      'msg': message,
    },
  };

  var response = async () => {
    try {
      var onlineUsers = await getOnlineUsers(ossClient);
      console.log('online users: %j', onlineUsers);
      var keys = Object.keys(onlineUsers);
      for (let i = 0; i < keys.length; i++) {
        if (keys[i] != deviceId) {
          var succ = await notify(keys[i], deviceId, message);
          console.log('Result:', keys[i], succ)
          if (!succ) {
            delete onlineUsers[keys[i]];
          }
        }
      }
      await setOnlineUsers(ossClient, onlineUsers);
      callback(null, resp);
    } catch (err) {
      console.error(err);
      callback(err);
    };
  }
  response();
};

var getOnlineUsers = async (ossClient) => {
  var usersKey = WORK_DIR + 'online.json';
  var users = {};
  try {
    var resp = await ossClient.get(usersKey);
    return JSON.parse(resp.content.toString());
  } catch (err) {
    return users;
  }
};

var setOnlineUsers = async (ossClient, users) => {
  var usersKey = WORK_DIR + 'online.json';
  await ossClient.put(usersKey, new Buffer(JSON.stringify(users)));
};

var notify = (deviceId, from, message) => {
  return new Promise((resolve, reject) => {
    try {
      var options = {
        method: 'POST',
        uri: AG_NOTIFY_URL,
        headers: {
          'x-ca-deviceid': deviceId,
        },
        body: {
          from: from,
          message: message
        },
        json: true
      };
      request(options).then(res => {
        console.log('notify res: %j', res);
        resolve(true);
      }).catch((err) => {
        console.log('notify error1: %j', err);
        resolve(false)
      })
    } catch (err) {
      console.log('notify error2: %j', err);
      resolve(false)
    }
  })

};

var getOSSClient = function (context) {
  return new OSS({
    accessKeyId: context.credentials.accessKeyId,
    accessKeySecret: context.credentials.accessKeySecret,
    stsToken: context.credentials.securityToken,
    region: 'oss-' + context.region,
    internal: true,
    secure: true,
    bucket: BUCKET,
  });
};
